<?php

namespace bc\model\marquee;

use bc\ar\MActiveRecord;

class StatisticsModel extends MActiveRecord
{
	public $autoId = 'statistics_id';
	
	public static function tableName()
	{
		return '{{%marquee_statistics}}';
	}
	
	

	/**
	 * 开启事务方式执行插入数据
	 * @param int $marquee_id
	 * @param int $viewCount
	 */
	public function tractionUpdate($marquee_id, $viewCount)
	{
		$transaction = $this->getDb()->beginTransaction();
		try
		{
			$today = date('Y-m-d');
			$current = date('Y-m-d H:i:s');
				
			$lastSelectSql = 'SELECT statistics_id FROM ' . self::getTableSchema()->name . ' WHERE marquee_id = ' . $marquee_id . ' AND start_time >= "' . $today . '" ORDER BY statistics_id DESC LIMIT 1';
				
			$last = $this->getDb()->createCommand($lastSelectSql)->queryOne();
			if($last)
			{
				
				$updateSql = 'UPDATE ' . self::getTableSchema()->name . ' SET auto = 2, view_count = ' . $viewCount . ', end_time = "' .  $current   .'" WHERE statistics_id = ' . $last['statistics_id'];
				$this->getDb()->createCommand($updateSql)->execute();
			}
				
			//更新主表数据
			$updateMainSql = 'UPDATE ' . MarqueeModel::getTableSchema()->name . ' SET view_count = 0 WHERE id = ' . $marquee_id;
			$this->getDb()->createCommand($updateMainSql)->execute();
			
			
			$insertSql = 'INSERT ' . self::getTableSchema ()->name . "(auto, view_count, start_time, end_time, marquee_id, create_time) VALUES (1, 0, '{$current}', '{$current}', {$marquee_id}, '{$current}')";
			$this->getDb()->createCommand($insertSql)->execute();
	
			$transaction->commit();
			return true;
		}
		catch (\Exception $e)
		{
			$transaction->rollBack();
			throw $e;
		}
	}
}

